<!--设备激活-->
<template>
  <div class="activation">
    <el-form :inline="true" class="search-form">
      <el-form-item class="title">
        设备激活
      </el-form-item>
      <el-form-item>
        <!-- <el-cascader
          v-model="categoryValue"
          :options="categoryList"
          placeholder="所有品类"
          popper-class="cascader-custom-popper"
          :props="{ checkStrictly: true }"
          @change="handleCategory">
        </el-cascader> -->
        <a-cascader
          v-model="categoryValue"
          :options="categoryList"
          placeholder="所有品类"
          clearable
          @change="handleCategory">
        </a-cascader>
      </el-form-item>
      <el-form-item>
        <el-select v-model="productValue" placeholder="所有产品" @change="handleProduct">
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="header">
      <div class="today-activation">
        <div class="left">
          <div class="head">今日激活设备数</div>
          <div class="num">{{ devicesData.tdevices }}</div>
        </div>
        <div class="right">昨日：{{ devicesData.ydevices }}</div>
      </div>
      <div class="lasts7-activation">
        <div class="left">
          <div class="head">近7日激活设备数量</div>
          <div class="num">{{ devicesData.nearly7Devices }}</div>
        </div>
        <div class="right">上7日：{{ devicesData.last7Devices }}</div>
      </div>
      <div class="accumulate-activation">
        <div class="left">
          <div class="head">累计激活设备数</div>
          <div class="num">{{ devicesData.totalDevices }}</div>
        </div>
        <div class="right"></div>
      </div>
    </div>
    <div class="search">
      <div class="name">激活趋势</div>

      <div class="search-right">
        <div class="tab">
          <div class="day" :class="{'active': dateType === 'day'}" @click="handleDate('day')">按日查询</div>
          <div class="mounth" :class="{'active': dateType === 'mounth'}" @click="handleDate('mounth')">按月查询</div>
        </div>
        <el-date-picker
          v-show="dateType === 'day'"
          ref="datePicker"
          v-model="dayValue"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          :picker-options="pickerOptions"
          clearable
          @blur="isRestart = true"
          @change="handleFormat">
        </el-date-picker>
        <el-date-picker
          v-show="dateType === 'mounth'"
          ref="monthPicker"
          v-model="mounthValue"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          :picker-options="pickerMounthOptions"
          clearable
          @blur="isRestart = true"
          @change="handleFormat">
        </el-date-picker>
      </div>
    </div>
    <div class="activation-box">
      <div class="header">
        <div class="">激活设备数</div>
        <el-button type="primary" size="14" @click="handleExports('activated')">导出</el-button>
      </div>
      <div id="main" ref="activationEcharts" style="height: 420px"></div>
    </div>
    <div class="activation-box">
      <div class="header">
        <div class="">累计激活设备数</div>
        <el-button type="primary" size="14" @click="handleExports('totalActivated')">导出</el-button>
      </div>
      <div id="main" ref="accumulateDevicesEcharts" style="height: 420px"></div>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/title'
import { activatedDevice, statisticalExport, product } from '@/api/device-data/device'
import { deviceCategories } from '@/api/product/create-product'
// 按需引入 Cascader 组件
import { Cascader } from 'ant-design-vue'
export default {
  name: 'deviceActivation',
  components: {
    'a-cascader': Cascader
  },
  data() {
    return {
      dayValue: [moment().subtract(7, 'days').format('YYYY-MM-DD'), moment().subtract(1, 'days').format('YYYY-MM-DD')],
      mounthValue: [moment(moment().format("YYYY-MM-DD")).subtract(5, 'months').startOf('month').format('YYYY-MM-DD'), moment().format("YYYY-MM-DD")],
      dateType: 'day', // 日期类型 day选择天 mounth选择月
      startDay: moment().subtract(7, 'days').format('YYYY-MM-DD'), // 开始时间 天
      endDay: moment().subtract(1, 'days').format('YYYY-MM-DD'), // 结束时间 天
      startMounth: '', // 开始时间 月
      endMounth: '', // 结束时间 月
      categoryValue: [], // 级联筛选品类列表
      categoryFilterValue: '', // 接口传参产品大类+小类拼接
      categoryList: [], // 品类列表
      rawData: [], // 放原始JSON数据
      productOptions: [], // 产品筛选列表
      productValue: '', // 产品id
      devicesData: {}, // 设备数据
      activationEchartsX: [], // 激活设备数x轴数据
      activationEchartsY: [], // 激活设备数y轴数据
      accumulateDevicesEchartsX: [], // 累计激活设备数x轴数据
      accumulateDevicesEchartsY: [], // 累计激活设备数y轴数据
      productIds: [], // 选中的产品id集合
      isComponentAlive: true
    }
  },
  computed: {
    pickerOptions() {
      const self = this // 保存组件实例的引用
      return {
        onPick: ({ maxDate, minDate }) => {
          self.isRestart = false
          self.pickerMinDate = minDate ? minDate.getTime() : ''
          if (maxDate) {
            self.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          const today = new Date()
          if (self.pickerMinDate !== '') {
            const oneYearInMilliseconds = 61 * 24 * 3600 * 1000 // 62天
            const minTime = self.pickerMinDate - oneYearInMilliseconds
            const maxTime = self.pickerMinDate + oneYearInMilliseconds
            // 禁用超过允许的日期范围和未来的日期
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > today.getTime()
          }
          return time.getTime() > today.getTime() // 禁用未来的日期
        }
      }
    },
    pickerMounthOptions() {
      return {
        onPick: ({ maxDate, minDate }) => {
          self.isRestart = false
          self.pickerMinDate = minDate ? minDate.getTime() : ''
          if (maxDate) {
            self.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          const today = new Date()
          const currentMonthLastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0) // 当月的最后一天
          // 禁用所有超过当月的未来日期
          if (time.getTime() > currentMonthLastDay.getTime()) {
            return true
          }
          if (self.pickerMinDate !== '') {
            const oneYearLater = new Date(new Date(self.pickerMinDate).setMonth(new Date(self.pickerMinDate).getMonth() + 11))
            const oneYearFront = new Date(new Date(self.pickerMinDate).setMonth(new Date(self.pickerMinDate).getMonth() - 11))
            return time.getTime() > currentMonthLastDay.getTime() || time.getTime() < oneYearFront || time.getTime() > oneYearLater
          }
          return false
        }
      }
    }
  },
  mounted() {
    this.queryCategory()
    this.queryProduct()
  },
  beforeDestroy() {
    this.isComponentAlive = false
    // 在组件销毁之前清理 ECharts 实例
    if (this.activationEcharts) {
      // 使用 echarts 的 dispose 方法清理图表实例
      this.activationEcharts.dispose()
      this.activationEcharts = null
    }
    if (this.accumulateDevicesEcharts) {
      // 使用 echarts 的 dispose 方法清理图表实例
      this.accumulateDevicesEcharts.dispose()
      this.accumulateDevicesEcharts = null
    }
  },
  methods: {
    init() {
      const params = {
        productIds: this.productIds,
        type: this.dateType,
        startDate: this.dateType === 'day' ? this.startDay : this.startMounth,
        endDate: this.dateType === 'day' ? this.endDay : this.endMounth
      }
      activatedDevice(params).then(res => {
        this.devicesData = res.data.data
        this.activationEchartsX = []
        this.activationEchartsY = []
        this.accumulateDevicesEchartsX = []
        this.accumulateDevicesEchartsY = []
        res.data.data.activatedDevicesList.forEach(item => {
          this.activationEchartsX.push(item.date)
          this.activationEchartsY.push(item.value)
        })
        res.data.data.totalActivatedDevicesList.forEach(item => {
          this.accumulateDevicesEchartsX.push(item.date)
          this.accumulateDevicesEchartsY.push(item.value)
        })

        if (this.isComponentAlive) {
          // 创建 ECharts 实例
          const activationEcharts = echarts.init(this.$refs.activationEcharts)
          const accumulateDevicesEcharts = echarts.init(this.$refs.accumulateDevicesEcharts)
          window.addEventListener('resize', () => {
            activationEcharts.resize()
            accumulateDevicesEcharts.resize()
          })
          activationEcharts.showLoading(
            {
              text: '',
              color: '#275FE8' // 更改图标的颜色
            }
          )
          accumulateDevicesEcharts.showLoading(
            {
              text: '',
              color: '#275FE8' // 更改图标的颜色
            }
          )
          // 调用 setOption 方法配置图表
          activationEcharts.setOption({
            xAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.4)' // 设置 x 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              data: this.activationEchartsX
            },
            yAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.4)' // 设置 y 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              splitLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)'
                }
              }
            },
            tooltip: {
              // 自定义tooltip的文案
              formatter: (params) => {
                return `${params.name} 激活设备数：${params.value}`
              }
            },
            series: [{
              name: '数据',
              type: 'line',
              symbol: 'circle', // 设置圆点样式
              symbolSize: 6, // 设置圆点大小
              itemStyle: {
                color: '#275FE8', // 设置数据圆点颜色
                opacity: 1 // 设置圆圈透明度为1，即实心圆圈
              },
              lineStyle: {
                width: 1, // 设置数据线宽度为0，即去掉横线
                color: '#275FE8' // 设置数据线颜色
              },
              data: this.activationEchartsY
            }]
          })
          // 调用 setOption 方法配置图表
          accumulateDevicesEcharts.setOption({
            xAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.4)' // 设置 x 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              data: this.accumulateDevicesEchartsX
            },
            yAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.4)' // 设置 y 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              splitLine: {
                // show: false // 设置是否显示 Y 轴的分隔线
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)'
                }
              }
            },
            tooltip: {
              // 自定义tooltip的文案
              formatter: (params) => {
                return `${params.name} 累计激活设备数：${params.value}`
              }
            },
            series: [{
              name: '数据',
              type: 'line',
              symbol: 'circle', // 设置圆点样式
              symbolSize: 6, // 设置圆点大小
              itemStyle: {
                color: '#275FE8', // 设置数据圆点颜色
                opacity: 1 // 设置圆圈透明度为1，即实心圆圈
              },
              lineStyle: {
                width: 1, // 设置数据线宽度为0，即去掉横线
                color: '#275FE8' // 设置数据线颜色
              },
              data: this.accumulateDevicesEchartsY
            }]
          })
          activationEcharts.hideLoading()
          accumulateDevicesEcharts.hideLoading()
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 查询产品品类
    queryCategory() {
      deviceCategories().then(res => {
        this.rawData = res.data.data.categories
        this.categoryList = this.rawData.map(std => ({
          label: std.standardCategory,
          value: std.standardCategory,
          children: std.primaryClassification.map(primary => ({
            label: primary.category,
            value: primary.category,
            children: primary.secondClassification.map(second => ({
              label: second.name,
              value: second.categoryCode
            }))
          }))
        }))
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 查询产品
    queryProduct() {
      const params = {
        category: '',
        categoryCode: this.categoryFilterValue
      }
      // if (this.categoryFlag === 2) {
      //   params = {
      //     category: '',
      //     categoryCode: this.categoryFilterValue === 'ALL' ? '' : this.categoryFilterValue
      //   }
      // } else {
      //   params = {
      //     category: this.categoryFilterValue === 'ALL' ? '' : this.categoryFilterValue,
      //     categoryCode: ''
      //   }
      // }
      this.productIds = []
      product(params).then(res => {
        this.productOptions = res.data.data
        // 将对象添加到数组的第一个位置
        const newObject = {
          productId: "ALL",
          productName: "所有产品"
        }
        this.productOptions.unshift(newObject)
        this.productOptions?.map(item => {
          if (item.productId !== 'ALL') {
            this.productIds.push(item.productId)
          }
        })
        this.init()
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 选择品类
    handleCategory(value) {
      this.categoryFilterValue = value[value.length - 1]
      this.productValue = ''
      this.queryProduct()
    },
    // 选择产品
    handleProduct(val) {
      this.productIds = []
      if (val === 'ALL') {
        this.queryProduct()
      } else {
        this.productIds.push(val)
        this.init()
      }
    },
    // 日期选择切换
    handleDate(type) {
      this.dateType = type
      if (type === 'day') {
        // this.$refs.mounthPicker?.hidePicker()
        // this.$nextTick(() => {
        //   this.$refs.datePicker.showPicker = true
        // })
      } else {
        this.startMounth = moment(moment().format("YYYY-MM-DD")).subtract(5, 'months').startOf('month').format('YYYY-MM-DD')
        this.endMounth = moment().format("YYYY-MM-DD")
        this.mounthValue = [this.startMounth, this.endMounth]
        // this.$refs.dayPicker?.hidePicker()
        // this.$nextTick(() => {
        //   this.$refs.mounthPicker.showPicker = true
        // })
      }
      this.init()
    },
    // 日期选择
    handleFormat(val) {
      if (this.dateType === 'day') {
        this.startDay = moment(val[0]).format("YYYY-MM-DD")
        this.endDay = moment(val[1]).format("YYYY-MM-DD")
      } else {
        this.startMounth = moment(val[0]).format("YYYY-MM-DD")
        this.endMounth = moment(val[1]).endOf('month').format("YYYY-MM-DD")
      }
      this.init()
    },
    // 导出
    handleExports(dataType) {
      const params = {
        productIds: this.productIds,
        type: this.dateType,
        startDate: this.dateType === 'day' ? this.startDay : this.startMounth,
        endDate: this.dateType === 'day' ? this.endDay : this.endMounth,
        dataType: dataType
      }
      statisticalExport(params).then(res => {
        this.exportBlobFile(res)
      }).catch(err => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.activation {
  .search-form {
    .title {
      font-weight: 400;
      color: #252525;
      margin-right: 56px;

      ::v-deep .el-form-item__content {
        font-size: 18px;
      }
    }

    ::v-deep .el-form-item {
      margin-right: 32px;
    }
  }

  .header {
    display: flex;

    .today-activation,
    .lasts7-activation,
    .accumulate-activation {
      background: rgba(39, 95, 232, 0.05);
      margin-right: 20px;
      padding: 15px;
      display: flex;
      justify-content: space-between;

      .left {
        margin-right: 20px;

        .head {
          font-size: 14px;
          font-weight: 400;
          color: #252525;
        }

        .num {
          font-size: 30px;
          font-weight: 500;
          color: #275FE8;
        }
      }

      .right {
        width: 77px;
        float: right;
        font-size: 14px;
        font-weight: 400;
        color: #252525;
        margin-top: 33px;
      }
    }

    // .accumulate-activation {
    //   padding-right: 129px;
    // }
  }

  .search {
    display: flex;
    justify-content: space-between;
    align-content: center;
    margin-top: 37px;

    .name {
      padding: 10px;
      font-size: 18px;
      font-weight: 400;
      color: #252525;
      background: rgba(39, 95, 232, 0.1);
    }

    .search-right {
      display: flex;
      align-items: center;

      .tab {
        margin-right: 16px;
        display: flex;
        align-items: center;

        .day,
        .mounth {
          width: 88px;
          height: 32px;
          line-height: 32px;
          background: rgba(0, 0, 0, 0.05);
          border-radius: 4px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.4);
          font-size: 14px;
          text-align: center;
          cursor: pointer;
        }
        .day {
          margin-right: 16px;
        }

        .active {
          background: rgba(39,95,232,0.1);
          border: 1px solid rgba(39,95,232,0.4);
          color: #275FE8;
        }
      }
    }

    ::v-deep .el-date-editor--daterange.el-input__inner,
    ::v-deep .el-date-editor--monthrange.el-input, .el-date-editor--monthrange.el-input__inner {
      width: 243px;
    }

    ::v-deep .el-range-separator {
      color: #636B76;
      padding: 0 20px 0 5px;
    }
  }

  .activation-box {
    margin-top: 32px;

    .header {
      display: flex;
      justify-content: space-between;
    }
  }

  .ant-cascader-picker,
  .el-select {
    width: 388px;
  }

  ::v-deep .ant-cascader-picker:focus .ant-cascader-input,
  ::v-deep .ant-input:focus,
  ::v-deep .ant-input:focus {
    border-color: #275FE8;
  }
}
</style>
<style>
.ant-cascader-menu-item:hover {
  background: #F5F7FA;
}
</style>
